package com.qf.fmall2202.user.shiro;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall2202.user.entity.User;
import com.qf.fmall2202.user.service.IUsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class CustomRealm extends AuthorizingRealm {

    @Autowired
    IUsersService usersService;

    /**
     * 获取角色和权限信息
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {


        return null;

    }


    /**
     * 获取身份信息
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {


        final String username = (String) token.getPrincipal();

        final User dbuser = usersService.getOne(new QueryWrapper<User>().eq("username", username));

        if (dbuser==null){  // 用户不存在
            throw new UnknownAccountException();
        }

        return new SimpleAuthenticationInfo(dbuser, dbuser.getPassword(), ByteSource.Util.bytes(dbuser.getSalt())
                , this.getName());

    }
}
